package com.cskaoyan.demo.servlet;

import com.cskaoyan.bean.User;
import com.cskaoyan.demo.mapper.UserMapper;
import com.cskaoyan.utils.MyBatisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/list")
public class GetUsersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("收到请求！");
        // 得到userMapper
        UserMapper userMapper = MyBatisUtil.getUserMapper();
        // 执行mapper中的SQL方法获得List
        List<User> allUserList = userMapper.getAllUserList();
        // 释放资源
        MyBatisUtil.release();

//        System.out.println("allUserList = " + allUserList);

        allUserList.forEach(user -> {
            if (user.getId() >= 40 && user.getId() <= 50) {
                try {
                    // 打印到页面中
                    resp.getWriter().println("user" + user.getId() + " --> " + user);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("user" + user.getId() + " --> " + user);
            }
        });
    }
}